package com.hyny.framework.platform.system.exception;

import com.hyny.framework.platform.system.utils.bean.Result;
import com.hyny.framework.platform.system.utils.enums.ResultEnum;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.SignatureException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.authentication.LockedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理类
 */
@Slf4j
@RestControllerAdvice
public class GlobalException {

    @ExceptionHandler
    public Result customException(Exception ex) {
        log.error("异常信息：{}", ex.toString());
        ex.printStackTrace();
        if (ex instanceof ExpiredJwtException) { // Token过期
            return Result.error(ResultEnum.TOKEN_PAST);
        } else if (ex instanceof SignatureException || ex instanceof MalformedJwtException) { // Token无效
            return Result.error(ResultEnum.TOKEN_ERROR);
        } else if (ex instanceof BadCredentialsException) { // 登录认证失败（密码错误）
            return Result.error(ResultEnum.AUTH_PASSWORD_ERROR);
        } else if (ex instanceof InternalAuthenticationServiceException) { // 登录认证失败（账户不存在）
            return Result.error(ResultEnum.AUTH_USERNAME_ERROR);
        } else if (ex instanceof AccessDeniedException) { // 登录鉴权失败
            return Result.error(ResultEnum.AUTH_FAIL);
        } else if (ex instanceof LockedException) { // 登录鉴权失败
            return Result.error(ex.getMessage());
        } else if (ex instanceof HttpMessageNotReadableException) { //参数异常
            return Result.error(ResultEnum.PARAM_ERRROR);
        } else if (ex instanceof CommonException) { //自定义通用异常
            return Result.error(((CommonException) ex).getExceptionMessage());
        } else { // 其他未处理异常
            return Result.error(ResultEnum.ERROR,ex.getMessage());
        }

    }
}
